<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Code Igniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package		CodeIgniter
 * @author		Rick Ellis
 * @copyright	Copyright (c) 2006, pMachine, Inc.
 * @license		http://www.codeignitor.com/user_guide/license.html
 * @link		http://www.codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Code Igniter Richmail Class
 *
 * Adds inline images and base64 cache to base Email library
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Libraries
 * @author		Jan Willem Penterman
 * @link		http://www.shapers.nl/lab/ci/richmail
 *
 * Version 0.2 - updated 2007-05-14 by Toby Beresford to work with Code Igniter 1.5.3
 */


class MY_Email extends CI_Email
{
	var $imagepath			= ''; 	// path to directory that is prepended to the relative
											// path to images in the email template view.

	var $base64cache		= false;		// use config file to set to true and gain some speed
	var $base64path			= null;			// null tries to store cache in same dir as source file.
											// if set, it doesn't need a trailing '/'
	var $base64clear		= true;			// true deletes cache on Richmail::clear()
	var $base64ext			= "b64";		// extension name of base encoded files

	var $_attach_id			= array();
	var $_cache_name		= array();

	/**
	 * Config settings
	 *
		$config["mailtype"]  	= "html";		// should be "html"
		$config["multipart"] 	= "related";	// should be "related"!
		$config["base64cache"]	= false;		// chached base64 encoded files
	 *
     * @access	public
	 * @var		array
	 */
	var $config = array
	(
	 	'mailtype'	=> 'html',
		'multipart'	=> 'related',
		'base64cache' => false
	);
	/**
	 * Constructor - Sets Richmail/Email Preferences
	 *
	 * The constructor can be passed an array of config values
	 */
	function MY_Email($config = array())
	{

		parent::CI_Email($config);
	}
	// END MY_mail()

	// --------------------------------------------------------------------

	/**
	 * Initialize the Email Data
	 *
	 * @access	public
	 * @return	void
	 */
	function clear($clear_attachments = FALSE)
	{
        if ($clear_attachments !== FALSE)
        {
            if($this->base64cache && $this->base64clear) {
            	foreach($this->_cache_name as $cachename) {
            		@unlink($cachename);
            	}
            	$this->_cache_name = array();
            }
            $this->_attach_id   = array();
        }
        parent::clear($clear_attachments);
	}
  	// END clear()

	// --------------------------------------------------------------------

	/**
	 * Assign file attachments
	 *
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	function attach($filename, $disposition = 'attachment')
	{
		parent::attach($filename, $disposition);
		$attach_id = $disposition == 'inline' ? md5($filename).".".next(explode('.', basename($filename))) : null;
		$this->_attach_id[] = $attach_id;
		if($disposition == "inline") {
			return "cid:".$attach_id;
		}

	}
  	// END attach()

	// --------------------------------------------------------------------

	/**
	 * Searches for images in HTML input $message (current only HTML-attributes,
	 * no CSS, attaches those images as inline attachments and replaces the
	 * URL's with Content-Id's (cid:)
	 *
	 * @access	public
	 * @return	string
	 */
	function inline(& $message)
	{
		$ci = & get_instance();

		preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
		if(isset($images[2]))
		{
			foreach($images[2] as $i => $url)
			{
				$path = $this->imagepath.str_replace($ci->config->item('base_url'), "", $url);
				$cid  = $this->attach($path, "inline");
				$message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
			}
		}
		return $message;
	}
	// -------------------------------------------------------------------

	/**
	 * Build Final Body and attachments. Equal to Email::_build_message(),
	 * except for caching base64 encoded files, to speed up email building.
	 *
	 * @access	public
	 * @return	void
	 */
	function _build_message()
	{
		$this->_set_boundaries();
		$this->_write_headers();

		$hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';

		switch ($this->_get_content_type())
		{
			case 'plain' :

				$hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
				$hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();

				if ($this->_get_protocol() == 'mail')
				{
					$this->_header_str .= $hdr;
					$this->_finalbody = $this->_body;

					return;
				}

				$hdr .= $this->newline . $this->newline . $this->_body;

				$this->_finalbody = $hdr;
				return;

			break;
			case 'html' :

				$hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline;
				$hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
				$hdr .= "--" . $this->_alt_boundary . $this->newline;

				$hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
				$hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
				$hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;

				$hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
				$hdr .= "Content-Transfer-Encoding: quoted/printable";

				if ($this->_get_protocol() == 'mail')
				{
					$this->_header_str .= $hdr;
					$this->_finalbody = $this->_body . $this->newline . $this->newline . "--" . $this->_alt_boundary . "--";

					return;
				}

				$hdr .= $this->newline . $this->newline;
				$hdr .= $this->_body . $this->newline . $this->newline . "--" . $this->_alt_boundary . "--";

				$this->_finalbody = $hdr;
				return;

			break;
			case 'plain-attach' :

				$hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline;
				$hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
				$hdr .= "--" . $this->_atc_boundary . $this->newline;

				$hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
				$hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();

				if ($this->_get_protocol() == 'mail')
				{
					$this->_header_str .= $hdr;

					$body  = $this->_body . $this->newline . $this->newline;
				}

				$hdr .= $this->newline . $this->newline;
				$hdr .= $this->_body . $this->newline . $this->newline;

			break;
			case 'html-attach' :

				$hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline;
				$hdr .= $this->_get_mime_message() . $this->newline . $this->newline;
				$hdr .= "--" . $this->_atc_boundary . $this->newline;

				$hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
				$hdr .= "--" . $this->_alt_boundary . $this->newline;

				$hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
				$hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
				$hdr .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;

				$hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
				$hdr .= "Content-Transfer-Encoding: quoted/printable";

				if ($this->_get_protocol() == 'mail')
				{
					$this->_header_str .= $hdr;

					$body  = $this->_body . $this->newline . $this->newline;
					$body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
				}

				$hdr .= $this->newline . $this->newline;
				$hdr .= $this->_body . $this->newline . $this->newline;
				$hdr .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;

			break;
		}

		$attachment = array();

		$z = 0;

		for ($i=0; $i < count($this->_attach_name); $i++)
		{
			$filename = $this->_attach_name[$i];
			$basename = basename($filename);
			$ctype = $this->_attach_type[$i];

			if ( ! file_exists($filename))
			{
				$this->_set_error_message('email_attachment_missing', $filename);
				return FALSE;
			}

			$h  = "--".$this->_atc_boundary.$this->newline;
			$h .= "Content-type: ".$ctype."; ";
			$h .= "name=\"".$basename."\"".$this->newline;
			$h .= "Content-Transfer-Encoding: base64".$this->newline;
			$h .= "Content-Disposition: ".$this->_attach_disp[$i].";";
			$h .= " filename=\"".$basename."\"".$this->newline;
			if($this->_attach_id[$i])
			{
				$h .= "Content-Id: <".$this->_attach_id[$i].">".$this->newline;
			}

			$attachment[$z++] = $h;

			$loadedfromcache = false;

			if($this->base64cache == true)
			{
				$cachename = basename($filename).".".$this->base64ext;
				$cachename = $this->base64path ? $this->base64path."/".$cachename : dirname($filename)."/".$cachename;
				$fp = @fopen($cachename, 'r');
				if (!$fp)
				{
					$this->_set_error_message('email_attachment_cache_unreadable', $cachename);
				}
				else
				{
					$file = filesize($cachename) + 1;
					$attachment[$z++] = fread($fp, $file);
					fclose($fp);
					$loadedfromcache  = true;
					$this->_cache_name[] = $cachename;
				}
			}

			if(!$loadedfromcache) {
				$file = filesize($filename) +1;

				if (! $fp = fopen($filename, 'r'))
				{
					$this->_set_error_message('email_attachment_unreadable', $filename);
					return FALSE;
				}
				$base64 = chunk_split(base64_encode(fread($fp, $file)));
				fclose($fp);
				if($this->base64cache == true)
				{
					$fp = @fopen($cachename, 'w+');
					if(!$fp)
					{
						$this->_set_error_message('email_attachment_cache_unwritable', $cachename);
					}
					else {
						fwrite($fp, $base64, strlen($base64));
						fclose($fp);
					}
				}
				$attachment[$z++] = $base64;
			}
		}

		if ($this->_get_protocol() == 'mail')
		{
			$this->_finalbody = $body . implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";

			return;
		}

		$this->_finalbody = $hdr.implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";

		return;
	}
  	// END _build_message()

}